/**
 * elancom Corporation copy right 2012 - 2015  
 *   
 * $Header: https://192.168.1.224/svn/elancom/product/elancom-platform/trunk/src/main/java/com/elancom/framework/util/BeanUtils.java 1034 2012-07-02 03:09:12Z lanzhouxue $
 * $Id: BeanUtils.java 1034 2012-07-02 03:09:12Z lanzhouxue $
 * $Author: lanzhouxue $
 * $Date: 2012-07-02 11:09:12 +0800 (Mon, 02 Jul 2012) $
 * $Revision: 1034 $
 */
package com.elancom.framework.commons.util;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;

/**
 * @author elancom
 * @date Apr 16, 2012
 */
public class BeanUtils {
	public static interface ValueFilter {
		public Object getValue(String name, Object value);
	}

	public static interface PropertyFilter {
		public Object getValue(String name, Object value);
	}

	@SuppressWarnings("unchecked")
	public static <T> T getPropertyValue(Object beab, String propertyName) {
		try {
			return (T) org.apache.commons.beanutils.BeanUtils.getProperty(beab, propertyName);
		} catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
			e.printStackTrace();
			return null;
		}
	}

	public static <T> T copyValue(T bean, Map<String, ?> mapValue) {
		try {
			org.apache.commons.beanutils.BeanUtils.populate(bean, mapValue);
		} catch (final Exception e) {
			throw new BeanCopyValueException();
		}
		return bean;
	}

	public static <T> T copyProperties(T dest, T orig) {
		try {
			org.apache.commons.beanutils.BeanUtils.copyProperties(dest, orig);
		} catch (IllegalAccessException | InvocationTargetException e) {
			e.printStackTrace();
		}
		return dest;
	}

	@SuppressWarnings("unused")
	private static void debug(Object obj) {
		if (obj == null) {
			return;
		}

		final StringBuilder sb = new StringBuilder();
		final Field[] fields = obj.getClass().getDeclaredFields();
		for (final Field field : fields) {
			field.setAccessible(true);
			sb.append("\t\t" + field.getName());
			if (field.getType().getName().equals(java.lang.String.class.getName())) {
				try {
					sb.append(":").append(field.get(obj)).append("\n");
				} catch (final Exception e) {
				}
			} else if (field.getType().getName().equals(java.lang.Integer.class.getName()) || field.getType().getName().equals("int")) {
				try {
					sb.append(":").append(field.getInt(obj)).append("\n");
				} catch (final Exception e) {
				}
			}
		}
	}
}
